<template>
  <view class="container">
    <!-- 技术分类标签 -->
    <view class="category-section" v-if="!categoryId">
      <view class="icon-alll" @click="showCategoryModal" :class="{ 'active': showModal }">
        <view class="hamburger-icon">
          <view class="line"></view>
          <view class="line"></view>
          <view class="line"></view>
        </view>
      </view>
      <scroll-view
        class="category-tabs" 
        scroll-x 
        scroll-with-animation 
        :scroll-left="scrollLeft"
        show-scrollbar="false"
      >
        <view class="category-tabs-wrapper">
          <view 
            class="tab-item" 
            v-for="(tab, index) in tabs" 
            :key="index"
            :class="{ active: current === index }"
            @click="handleChange(index)"
          >
            <text class="tab-name">{{ tab.categoryName }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 面试题列表 -->
    <view :class="{ 'with-category-padding ': categoryId, 'questions-section': true}">
      <view class="section-header">
        <view class="section-title">{{ currentCategoryName }}</view>
        <view class="question-count">{{ questions.length }}道题目</view>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <u-loading-icon mode="circle" size="28" text="加载中..."></u-loading-icon>
      </view>
      
      <view class="question-list" v-else>
          <view
            class="question-item"
            v-for="(item, index) in questions"
            :key="index"
            @click="viewQuestionDetail(item)"
            :style="{ animationDelay: (index < 10 ? index * 0.02 : 0) + 's' }"
          >
            <view class="question-main">
              <view class="question-header">
                <view class="question-number">{{ index + 1 }}</view>
                <view class="question-title">{{ item.title }}</view>
              </view>
<!--              <view class="question-note">{{ item.note.substring(0, 20) }}...</view>-->
            </view>
            <view class="question-meta">
              <difficulty-tag :difficulty="item.difficulty" />
              <view class="meta-item">{{ item.type || '中等' }}</view>
            </view>
          </view>
        <!-- 无数据时显示 -->
        <view v-if="questions.length === 0 && !loading" class="no-favorites">
          <image :src="'https://youke1.picui.cn/s1/2025/09/18/68cbfee87ade0.png'" class="empty-icon"></image>
          <view class="empty-text">暂无数据</view>
        </view>
      </view>
    </view>
    
    <!-- 分类选择模态框 -->
    <view class="category-modal" :class="{ 'show': showModal }" @click="hideCategoryModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">全部分类</text>
          <!-- 过滤开关 -->
          <view class="filter-section">
            <view class="filter-label">隐藏已掌握</view>
            <switch
                :checked="filterMastered"
                @change="toggleFilterMastered"
                color="var(--primary-color)" />
          </view>
          <view class="modal-close" @click="hideCategoryModal">
            <u-icon name="close" size="16" color="#999"></u-icon>
          </view>
        </view>
        <view class="modal-body">
          <view class="modal-tab-container">
            <view 
              class="modal-tab-item"
              v-for="(tab, index) in tabs"
              :key="index"
              :class="{ active: current === index }"
              @click="selectCategory(index)"
            >
              <text class="tab-name">{{ tab.categoryName }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import DifficultyTag from '@/components/difficulty-tag.vue';
import config from '@/common/config.js';

export default {
  components: {
    DifficultyTag
  },
  data() {
    return {
      current: 0,
      scrollLeft: 0,
      swiperHeight: '600px',
      searchKeyword: '',
      tabs: [],
      allQuestions: [],
      questions: [],
      categoryId: null,
      loadedTabs: [], // 记录已加载数据的tab
      currentCategoryName: '面试题',
      loading: false, // 添加加载状态
      showModal: false, // 添加模态框显示状态
      filterMastered: uni.getStorageSync('filterMastered') !== false // 从localStorage读取过滤设置，默认为true
    };
  },

  onLoad(options) {
    // 获取路由参数中的id
    if (options.categoryId) {
      // 如果传入的是categoryId，直接加载该分类下的问题
      this.categoryId = options.categoryId;
      this.currentCategoryName = decodeURIComponent(options.categoryName) || '面试题';
      this.loadQuestionsByCategory(this.categoryId);
    } else if (options.parentId) {
      // 如果传入的是parentId，加载该父级下的所有子分类作为tabs
      this.parentId = options.parentId;
      this.currentCategoryName = options.categoryName || '面试题';
      this.loadTabsData();
    }
  },

  mounted() {
    this.calculateSwiperHeight();
  },
  
  onShow() {
    // 页面显示时重新加载当前分类的数据，确保掌握状态的同步
    if (this.tabs.length > 0) {
      const categoryId = this.tabs[this.current].categoryId;
      this.loadQuestionsForTab(categoryId, this.current);
    } else if (this.categoryId) {
      this.loadQuestionsByCategory(this.categoryId);
    }
  },
  
  methods: {
    // 初始化默认数据
    initDefaultData() {
      this.tabs = [];
      this.allQuestions = [];
    },
    
    // 切换过滤已掌握题目开关
    toggleFilterMastered(e) {
      this.filterMastered = e.target.value;
      // 保存设置到localStorage
      uni.setStorageSync('filterMastered', this.filterMastered);
      // 重新加载当前分类的数据
      if (this.tabs.length > 0) {
        const categoryId = this.tabs[this.current].categoryId;
        this.loadQuestionsForTab(categoryId, this.current);
      } else if (this.categoryId) {
        this.loadQuestionsByCategory(this.categoryId);
      }
    },

    // 加载所有目录数据作为tabs
    loadTabsData() {
      // 获取当前页面栈
      const pages = getCurrentPages();
      // 获取当前页面实例
      const currentPage = pages[pages.length - 1];
      // 获取页面路由信息
      console.log('当前页面路由:', currentPage.route);
      console.log('当前页面参数:', currentPage.options);

      // 使用项目中已有的request方法直接调用接口获取所有目录数据
      this.loading = true; // 开始加载
      this.$request(`/interview/category/list?parentId=${currentPage.options.parentId || 0}`, 'GET')
        .then(res => {
          // 检查返回的数据是否为期望的JSON格式
          if (typeof res === 'string' && res.includes('Please enable JavaScript to continue')) {
            console.error('接口返回了HTML页面而非JSON数据');
            // 使用默认数据
            this.initDefaultData();
            return;
          }
          
          // 检查是否是认证失败的情况
          if (res.code === 401 || res.status === 401 || 
              (res.msg && res.msg.includes('认证')) || 
              (res.message && res.message.includes('认证'))) {
            console.error('认证失败:', res);
          }

          if (res.code === 200) {
            // 处理返回的数据，根据实际API返回结构转换为组件需要的格式
            this.tabs = res.rows.map(item => {
              return {
                categoryName: item.categoryName,
                categoryId: item.categoryId
              };
            });

            // 初始化问题数据和加载状态
            this.allQuestions = this.tabs.map(() => []);
            this.loadedTabs = []; // 初始化已加载tab记录数组

            // 如果有传入分类ID，默认选中该分类
            if (this.categoryId) {
              const tabIndex = this.tabs.findIndex(tab => tab.categoryId == this.categoryId);
              if (tabIndex !== -1) {
                this.current = tabIndex;
              }
            }

            // 只加载当前选中tab的数据，而非所有tab数据
            if (this.tabs.length > 0) {
              const currentIndex = this.current;
              const categoryId = this.tabs[currentIndex].categoryId;
              this.loadQuestionsForTab(categoryId, currentIndex);
              // 标记当前tab已加载
              this.loadedTabs.push(currentIndex);
            }
          } else {
            console.error('获取分类列表失败:', res);
            // 使用默认数据
            this.initDefaultData();
          }
        }).catch(err => {
          console.error('获取分类列表异常:', err);
          // 检查是否是认证错误
          // 使用默认数据
          this.initDefaultData();
        }).finally(() => {
          this.loading = false; // 加载完成
        });
    },

    // 根据分类ID加载问题数据
    loadQuestionsByCategory(categoryId) {
      this.loading = true; // 开始加载
      this.$request(`/interview/question/listWithStatus?categoryId=${categoryId}`, 'GET')
        .then(res => {
          if (res.code === 200) {
            // 处理返回的问题数据，根据实际API返回结构转换为组件需要的格式
            let questions = res.rows;
            
            // 根据开关状态决定是否过滤已掌握的题目
            if (this.filterMastered) {
              questions = questions.filter(item => !item.isMastered || item.isMastered !== 1);
            }
            
            this.questions = questions.map(item => {
              return {
                title: item.content || '暂无标题',
                note: item.analysis || '暂无描述',
                difficulty: item.difficulty || '中等',
                type: item.type || '中等',
                ...item
              };
            });
          } else {
            console.error('获取问题列表失败:', res);
            this.questions = [];
          }
        }).catch(err => {
          console.error('获取问题列表异常:', err);
          this.questions = [];
        }).finally(() => {
          this.loading = false; // 加载完成
        });
    },
    
    // 根据分类ID加载问题数据（用于tab切换）
    loadQuestionsForTab(categoryId, tabIndex) {
      this.loading = true; // 开始加载
      this.$request(`/interview/question/listWithStatus?categoryId=${categoryId}`, 'GET')
        .then(res => {
          if (res.code === 200) {
            // 处理返回的问题数据，根据实际API返回结构转换为组件需要的格式
            let questions = res.rows;
            
            // 根据开关状态决定是否过滤已掌握的题目
            if (this.filterMastered) {
              questions = questions.filter(item => !item.isMastered || item.isMastered !== 1);
            }
            
            this.questions = questions.map(item => {
              return {
                title: item.content || '暂无标题',
                note: item.analysis || '暂无描述',
                difficulty: item.difficulty || '中等',
                type: item.type || '中等',
                ...item
              };
            });
          } else {
            console.error('获取问题列表失败:', res);
            this.questions = [];
          }
        }).catch(err => {
          console.error('获取问题列表异常:', err);
          this.questions = [];
        }).finally(() => {
          this.loading = false; // 加载完成
        });
    },
    
    handleChange(value,type) {
      this.current = value;
      this.scrollToTab(value);
      this.currentCategoryName = this.tabs[value].categoryName;
      
      // 加载选中tab下的问题数据
      const categoryId = this.tabs[value].categoryId;
      this.loadQuestionsForTab(categoryId, value);
    },

    scrollToTab(index) {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this);
        query.select('.category-tabs').boundingClientRect();
        query.selectAll('.tab-item').boundingClientRect();
        
        query.exec((res) => {
          if (res[0] && res[1] && res[1][index]) {
            const containerRect = res[0];
            const tabRects = res[1];
            
            // 计算选中tab左侧到容器左侧的累计距离
            let offsetLeft = 0;
            for (let i = 0; i < index; i++) {
              offsetLeft += tabRects[i].width + 10; // 10是tab-item的margin-right值
            }
            
            // 计算准确的居中位置
            const containerWidth = containerRect.width;
            const selectedTabWidth = tabRects[index].width;
            // 计算目标位置：选中tab的中心点与容器中心点对齐时的scrollLeft值
            const targetScrollLeft = offsetLeft - (containerWidth - selectedTabWidth) / 2;
            
            // 确保滚动位置不为负数
            this.scrollLeft = Math.max(0, targetScrollLeft);
          } else {
            // 备用方案：基于固定宽度的计算
            const tabWidth = 80; // 假设每个tab平均宽度为80px
            this.scrollLeft = Math.max(0, index * tabWidth - 150);
          }
        });
      });
    },

    calculateSwiperHeight() {
      // 计算屏幕高度，设置swiper高度
      const systemInfo = uni.getSystemInfoSync();
      this.swiperHeight = (systemInfo.windowHeight - 250) + 'px'; // 减去其他元素高度
    },
    
    // 修改viewQuestionDetail方法，移除category参数
    viewQuestionDetail(item) {
      // 跳转到详情页
      uni.navigateTo({
        url: `/pages/question/detail?questionId=${encodeURIComponent(item.questionId)}&categoryId=${item.categoryId}`
      });
    },
    
    handleSearch() {
      if (this.searchKeyword.trim()) {
        uni.showToast({
          title: '搜索功能开发中',
          icon: 'none'
        });
      }
    },
    
    // 显示分类模态框
    showCategoryModal() {
      this.showModal = true;
    },
    
    // 隐藏分类模态框
    hideCategoryModal() {
      this.showModal = false;
    },

    // 选择分类
    selectCategory(index) {
      this.hideCategoryModal();
      this.handleChange(index);
    }
  }
}
</script>

<style lang="css">
@import '@/components/css/question.css';
</style>
